package com.cj.flowabletest.service;

import com.cj.flowabletest.model.AskForLeaveVo;
import com.cj.flowabletest.model.RespBean;
import com.cj.flowabletest.model.User;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.runtime.Execution;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author cc
 * @date 2025-03-03 16:12
 **/
@Service
public class AskForLeaveService {
    @Autowired
    RuntimeService runtimeService;

    @Transactional
    public RespBean askForLeave(AskForLeaveVo askForLeaveVo) {

        try {
            Map<String, Object> map = new HashMap<>();
            map.put("days",askForLeaveVo.getDays());
            map.put("approveUser",askForLeaveVo.getApproveUser());
            map.put("endTime",askForLeaveVo.getEndTime());
            map.put("startTime",askForLeaveVo.getStartTime());
            map.put("reason",askForLeaveVo.getReason());
            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            // 申请人
            map.put("applicant",user.getUsername());

            // 启动流程
            ProcessInstance pi = runtimeService.startProcessInstanceByKey("askforleave_demo",map);

            return RespBean.ok("请假申请已提交");
        } catch (Exception e) {
//            throw new RuntimeException(e);
            e.printStackTrace();
        }

        return RespBean.error("请假申请已提交失败");

    }

    public List<AskForLeaveVo> getUnapproveProcess() {

        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        List<AskForLeaveVo> list = new ArrayList<>();

        List<Execution> executions = runtimeService.createExecutionQuery().startedBy(user.getUsername()).list();
        for (Execution execution : executions) {
//            execution
            String executionId = execution.getId();
            Integer days = (Integer) runtimeService.getVariable(executionId, "days");
            String approveUser = (String) runtimeService.getVariable(executionId, "approveUser");
            Date startTime = (Date) runtimeService.getVariable(executionId, "startTime");
            Date endTime = (Date) runtimeService.getVariable(executionId, "endTime");
            String reason = (String) runtimeService.getVariable(executionId, "reason");

            list.add(new AskForLeaveVo(days,reason,startTime,endTime,approveUser,execution.getProcessInstanceId()));
        }



        return list;
    }
}
